﻿using FI.Dapper.Transaction;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using System.Text;
using System.Threading.Tasks;

namespace FI.Dapper.Transaction
{

    public class DapperTransactionScopeWrapper
    {
        private IDbConnection _connection;
        private IDbTransaction _transaction;

        public IDapperContext Context { get; private set; }

        private bool _disposed;

        public DapperTransactionScopeWrapper(IDapperContext Context)
        {
            this.Context = Context;
            _connection = Context.Connection;

            _transaction = _connection.BeginTransaction();

            CallContext.SetData("DapperContext", _transaction);
        }

        private void Commit()
        {
            try
            {
                _transaction.Commit();

            }
            catch
            {
                _transaction.Rollback();
                throw;
            }
            finally
            {
                CallContext.SetData("DapperContext", null);
                _transaction.Dispose();
            }
        }

        public void Dispose()
        {
            Commit();
            dispose(true);
            GC.SuppressFinalize(this);
        }

        private void dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_transaction != null)
                    {
                        _transaction.Dispose();
                        _transaction = null;
                    }
                    if (_connection != null)
                    {
                        _connection.Dispose();
                        _connection = null;
                    }
                }
                _disposed = true;
            }
        }

        ~DapperTransactionScopeWrapper()
        {
            dispose(false);
        }
    }


}
